Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

300
Visualizações
Django REST Framework - "Must be Device instance" error when calling PUT from javascript

I'm getting an error when trying to update an object instance using PUT using the rest framework: ValueError: Cannot assign "{'id': UUID('954...8b4')}": "DeviceConfig.device" must be a "Device" instance.

view defn:

class DeviceConfigViewSet(viewsets.ModelViewSet):
    #todo: secure
    authentication_classes = []
    queryset = DeviceConfig.objects.all().order_by('device')
    def get_queryset(self):
        device = self.get_renderer_context()["request"].query_params.get('device')
        if device:
            return DeviceConfig.objects.filter(device=Device(device=device))[0:]
        else:
            return self.queryset
    serializer_class = DeviceConfigSerializer

DeviceConfig model:

class DeviceConfig(models.Model):
    device = models.OneToOneField(Device,primary_key=True,on_delete=models.CASCADE)
    bpm = models.DecimalField(max_digits=22, decimal_places=3, blank=True, null=True, default=0.5)
    duty = models.DecimalField(max_digits=22, decimal_places=4, blank=True, null=True, default=0.022)
    ledState = models.IntegerField(
        default=255,
        validators=[MaxValueValidator(255), MinValueValidator(0)]
     )
    pressureMax = models.IntegerField( blank=True, null=True, default=70, validators=[MaxValueValidator(255), MinValueValidator(10)])

JS func FE side:

   function formSubmit(){
        var myForm = document.getElementById("config-form");
        var formObj = new FormData(myForm);
        var object = {};
        formObj.forEach(function(value, key){
            object[key] = value;
        });
        object["device"] = DEVICE_UUID;
        const putMethod = {
            method: 'PUT',
            headers: {
            'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
            },
            body: JSON.stringify(object) 
        }
        fetch("http://localhost:81/configs/"+DEVICE_UUID, putMethod);
    }

I've tried not sending the device ID from the front end but it gives me a 400 then the ol' goog search didn't turn up much for me this time, but I'm not quite sure how to send a Device instance from the client side besides by it's pk which is what I've tried

EDIT - DeviceConfigSerializer

class DeviceConfigSerializer(serializers.HyperlinkedModelSerializer):
    device = serializers.UUIDField(source='device.id')
    class Meta:
        model = DeviceConfig
        fields = ('device','bpm', 'duty','ledState','pressureMax')
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I worked it out. @JPG helped point in the right direction, it was the serializer - i was needlessly referencing device, which was screwing things up. I've removed it from the serializer and JS and all works well now. Thanks for pointing me in the right direction @JPG

Given the reference to the device ID was already in the url I was calling, there's no need to pass it in again. I'm still not quite sure how to interpret the error (insight appreciated) but my thoughts are it was attempting to assign a plain UUID where it needed a Device instance, which was not being handled in my serializer code as I thought it was.

Cheers

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda